<template>
  <div id="dialogDepartment">
    <el-dialog
      :title="isAdd ? '添加部门' : '编辑部门'"
      :visible.sync="dialogData.isShow"
      :before-close="labelHandleClose"
      width="550px"
    >
      <div class="form-box">
        <el-form ref="ruleForm" :model="form" :rules="formRules">
          <el-form-item label="上级部门" label-width="90px" prop="parentName">
            <el-input v-model="form.parentName" @focus="showSelectDepartment">
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="部门名称" label-width="90px" prop="deptName">
            <el-input v-model.trim="form.deptName"></el-input>
          </el-form-item>
          <el-form-item label="显示排序" label-width="90px" prop="orderNum">
            <el-input v-model.trim="form.orderNum"></el-input>
          </el-form-item>
          <el-form-item label="负责人" label-width="90px" prop="leader">
            <el-input v-model.trim="form.leader"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" label-width="90px" prop="phone">
            <el-input v-model.trim="form.phone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" label-width="90px" prop="email">
            <el-input v-model.trim="form.email"></el-input>
          </el-form-item>
          <el-form-item label="部门状态" label-width="90px">
            <template>
              <el-radio
                v-for="item in statusList"
                :key="item.dictValue"
                v-model="form.status"
                :label="item.dictValue"
              >
                {{ item.dictLabel }}
              </el-radio>
            </template>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="cancelLabel">
          取 消
        </el-button>
        <el-button
          type="success"
          :loading="loading"
          @click="confirmLabel('ruleForm')"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>
    <!-- 部门选择弹出框 -->
    <SelectDepartment
      ref="selectDepartment"
      width="480px"
      @getDepartName="getDepartName"
    ></SelectDepartment>
  </div>
</template>
<script>
import {
  departsDetail,
  editDeparts,
  addDeparts,
  repeatDeparts
} from '@/api/system/department' // 接口
import SelectDepartment from '@component/system/department/selectDepartment' // 选择部门
import { validateTelephone, validateEmail } from '@utils/validate'
import { sysNormalDisable } from '@utils/dictionariesFunc'
export default {
  name: 'RoleAddEdit',
  msg: '部门管理-新增/编辑弹窗',
  components: {
    SelectDepartment
  },
  props: ['dialogData'],
  data() {
    var valiSort = (rule, value, callback) => {
      if (!value) {
        callback(new Error('显示排序不能为空'))
      } else {
        if (isNaN(value)) {
          callback(new Error('显示排序必须为数字值'))
        } else {
          callback()
        }
      }
    }
    var valiPhone = (rule, value, callback) => {
      if (!value) {
        callback()
      } else {
        if (validateTelephone(value)) {
          callback()
        } else {
          callback(new Error('请输入正确11位手机号码'))
        }
      }
    }
    var valiEmail = (rule, value, callback) => {
      if (!value) {
        callback()
      } else {
        if (validateEmail(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }
    }
    //校验部门名称是否重复
    var valiDeptName = (rule, value, callback) => {
      let deptId = this.form.deptId || 0
      let obj = {
        deptName: value,
        parentId: this.form.parentId
      }
      repeatDeparts(
        deptId,
        obj,
        (response) => {
          if (response) {
            //true-有重复
            callback(new Error('部门名称已使用'))
          } else {
            //false-无重复
            callback()
          }
        },
        (res) => {
          callback(new Error('校验失败'))
        }
      )
    }
    return {
      isAdd: true, // 新增-true,编辑-false
      showTitle: '',
      loading: false,
      statusList: [],
      // 表单数据
      form: {
        parentName: '', // 上级部门名称
        deptId: '', // 部门id
        parentId: '', // 父级id
        deptName: '', // 部门名称
        orderNum: '', // 显示顺序
        leader: '', // 负责人
        phone: '', // 联系电话
        email: '', // 用户邮箱
        status: '0' // 状态0正常,1停用
      },
      formRules: {
        parentName: {
          required: true,
          message: '请选择上级部门'
        },
        orderNum: [{ required: true, validator: valiSort, trigger: 'blur' }],
        deptName: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { validator: valiDeptName, trigger: 'blur' }
        ],
        phone: { validator: valiPhone, trigger: 'blur' },
        email: { validator: valiEmail, trigger: 'blur' }
      }
    }
  },
  mounted() {
    this.getStatusList()
    this.isAdd = this.dialogData.type === 'add'
    this.showTitle = this.isAdd ? '新增' : '编辑'
    if (this.isAdd && !this.dialogData.params) {
      // 新增
      this.form.parentId = 100
      this.form.parentName = '大鹏教育'
    }
    if (this.isAdd && this.dialogData.params) {
      // 添加下级部门
      let params = this.dialogData.params
      this.form.parentId = params.deptId
      this.form.parentName = params.deptName
    }
    if (this.dialogData.type === 'edit') {
      this.form.deptId = this.dialogData.params
      this.getFormData()
    }
  },
  methods: {
    /* 获取部门状态 */
    async getStatusList() {
      let data = await sysNormalDisable(
        'sys_normal_disable',
        'sysNormalDisable'
      )
      this.statusList = this.statusList.concat(data)
    },
    /* 编辑时获取表单详情 */
    getFormData() {
      departsDetail(this.form.deptId, (response) => {
        let obj = response
        for (let key in this.form) {
          this.form[key] = obj[key]
        }
        if (obj.parentId === 0) {
          this.form.parentName = '大鹏教育'
        }
      })
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.dialogData.isShow = false
      this.dialogData.params = null
    },
    // 显示部门选择弹窗
    showSelectDepartment() {
      this.$refs.selectDepartment.showModel()
    },
    /* 确定 */
    confirmLabel(formName) {
      let _this = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.subForm()
        } else {
          return false
        }
      })
    },
    /* 提交表单 */
    subForm() {
      this.loading = true
      let obj = { ...this.form }
      delete obj.parentName
      if (this.isAdd) {
        // 新增
        addDeparts(
          obj,
          (response) => {
            this.$emit('refresh')
            this.cancelLabel()
          },
          (response) => {
            this.loading = false
            this.$message({
              message: this.showTitle + '失败，' + response.message,
              type: 'warning'
            })
          }
        )
      } else {
        // 编辑
        editDeparts(
          this.form.deptId,
          obj,
          (response) => {
            this.$emit('refresh')
            this.cancelLabel()
          },
          (response) => {
            this.loading = false
            this.$message({
              message: this.showTitle + '失败，' + response.message,
              type: 'warning'
            })
          }
        )
      }
    },
    /* 子组件选择菜单后，给上级菜单赋值 */
    getDepartName(selectNode) {
      if (!selectNode.id) return
      this.form.parentId = selectNode.id
      this.form.parentName = selectNode.name
    }
  }
}
</script>
<style lang="less" scoped>
#dialogDepartment {
  .el-dialog {
    border-radius: 4px;
    .el-dialog__header {
      border-bottom: 1px solid rgba(225, 228, 233, 1);
    }
  }
  .el-dialog__wrapper {
    z-index: 3000 !important;
  }
}
</style>
